package com.mjgy.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.common.utils.R;
import com.mjgy.entity.BroadCastEntity;
import com.mjgy.entity.BroadCastLikerEntity;
import com.mjgy.entity.BroadCastSignerEntity;
import com.mjgy.repository.BroadCastLikerRepository;
import com.mjgy.repository.BroadCastRepository;
import com.mjgy.repository.BroadCastSignerRepository;
import com.mjgy.service.BroadCastService;

/**
* @Description: TODO
* @author quanlq
* @date 2018年9月14日
* @version V1.0
*/
@Service("broadCastService")
public class BroadCastServiceImpl implements BroadCastService {
	
	@Autowired
	private BroadCastRepository broadCastRepository;
	@Autowired
	private BroadCastLikerRepository broadCastLikerRepository;
	@Autowired
	private BroadCastSignerRepository broadCastSignerRepository;
	@PersistenceContext
	private EntityManager entityManager;

	@Override
	@Transactional
	public void saveBroadCast(BroadCastEntity broadCastEntity) {
		broadCastRepository.deleteByUserId(broadCastEntity.getUserId());
		broadCastRepository.save(broadCastEntity);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<Map<String, Object>> findList(String sortKey, Integer sex, String city, Long userId, Integer page, Integer size) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		sql.append("bc.id");
		sql.append(",bc.type");
		sql.append(",bc.city");
		sql.append(",bc.date");
		sql.append(",bc.time");
		sql.append(",bc.description");
		sql.append(",bc.images");
		sql.append(",bc.forbid_images");
		sql.append(",bc.create_time");
		sql.append(",bc.like_num");
		sql.append(",bc.sign_num");
		sql.append(",bc.user_id");
		sql.append(",usr.nickname");
		sql.append(",usr.sex");
		sql.append(",usr.identity");
		sql.append(",usr.avatar");
		sql.append(",EXISTS(SELECT 1 FROM broast_cast_liker bcl WHERE bcl.broad_cast_id = bc.id AND bcl.liker_id = :userId) isLiker");
		sql.append(",EXISTS(SELECT 1 FROM broast_cast_signer bcs WHERE bcs.broad_cast_id = bc.id AND bcs.signer_id = :userId) isSigner");
		sql.append(",EXISTS(SELECT 1 FROM broast_cast_signer bcs WHERE bcs.broad_cast_id = bc.id AND bcs.is_dated = 1) isDating");
		sql.append(" FROM broad_cast bc");
		sql.append(" JOIN e_user usr ON bc.user_id = usr.id");
		sql.append(" WHERE bc.is_deleted = 0");
		sql.append(" AND usr.check_limit != 3");
		sql.append(" AND usr.status = 1");
		sql.append(" AND NOT EXISTS(SELECT 1 FROM e_user_defriend WHERE defriend = 1 AND ((active_id = :userId AND passive_id = bc.user_id)");
		sql.append(" OR ((active_id = bc.user_id AND passive_id = :userId))))");
		if(!StringUtils.isEmpty(city)){
			sql.append(" AND bc.city = :city");
		}
		if(!StringUtils.isEmpty(sex)){
			sql.append(" AND usr.sex = :sex");
		}
		if("date".equals(sortKey)){
			sql.append(" ORDER BY bc.date DESC");
		}else{
			sql.append(" ORDER BY bc.create_time DESC");			
		}
		sql.append(" LIMIT :pageIndex, :size");
		
		Query query = entityManager.createNativeQuery(sql.toString());
		if(!StringUtils.isEmpty(city)){
			query.setParameter("city", city);
		}
		if(!StringUtils.isEmpty(sex)){
			query.setParameter("sex", sex);
		}
		query.setParameter("userId", userId);
		query.setParameter("pageIndex", (page-1)*size);
		query.setParameter("size", size);
		List resultList = query.getResultList();
		
		List<Map<String, Object>> list = new ArrayList<>();
		for(Object row : resultList){
			Object[] cells = (Object[]) row;
			Map<String, Object> map = new HashMap<>();
			map.put("id", cells[0]);
			map.put("type", cells[1]);
			map.put("city", cells[2]);
			map.put("date", cells[3]);
			map.put("time", cells[4]);
			map.put("description", cells[5]);
			String images = cells[6] == null? "" : cells[6].toString();
			String forbidImages = cells[7] == null? "" : cells[7].toString();
			List<Map<String, Object>> imagesList = new ArrayList<>();
			if(!StringUtils.isEmpty(images)){
				String[] imageArr = images.split(",");
				for(String image : imageArr){
					Map<String, Object> temp = new HashMap<>();
					temp.put("url", image);
					if(forbidImages.indexOf(image) >= 0){
						temp.put("forbidden", 1);
					}else{
						temp.put("forbidden", 0);
					}
					imagesList.add(temp);
				}
			}
			map.put("images", imagesList);
			map.put("createTime", cells[8]);
			map.put("likeNum", cells[9]);
			map.put("signNum", cells[10]);
			map.put("userId", cells[11]);
			map.put("nickname", cells[12]);
			map.put("sex", cells[13]);
			map.put("identity", cells[14]);
			map.put("avatar", cells[15]);
			map.put("isLiker", cells[16]);
			map.put("isSigner", cells[17]);
			map.put("isDating", cells[18]);
			list.add(map);
		}
		
		return list;
	}

	@Override
	@Transactional
	public R like(BroadCastLikerEntity broadCastLikerEntity) {
		broadCastRepository.increaseLikeNum(broadCastLikerEntity.getBroadCastId());
		broadCastLikerRepository.save(broadCastLikerEntity);
		return R.success();
	}

	@Override
	public R signUp(BroadCastSignerEntity broadCastSignerEntity) {
		broadCastRepository.increaseSignNum(broadCastSignerEntity.getBroadCastId());
		broadCastSignerRepository.save(broadCastSignerEntity);
		return R.success();
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<Map<String, Object>> findSignerList(Long broadCastId, Integer page, Integer size) {
		//将所有报名人状态设为已阅
		broadCastSignerRepository.checkBroadCastSigner(broadCastId);
		
		List rows = broadCastSignerRepository.findSignerList(broadCastId, page, size);
		
		List<Map<String, Object>> list = new ArrayList<>();
		for(Object row : rows){
			Object[] cells = (Object[]) row;
			Map<String, Object> map = new HashMap<>();
			map.put("id", cells[0]);
			map.put("nickname", cells[1]);
			map.put("avatar", cells[2]);
			map.put("isDated", cells[3]);
			list.add(map);
		}
		
		return list;
	}

	@Override
	public void updateStatus(Integer isDeleted, Long userId) {
		broadCastRepository.updateStatus(isDeleted, userId);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, Object> findByUserId(Long userId, Long viewerId) {
		List rows = broadCastRepository.findByUserId(userId, viewerId);
		Map<String, Object> map = new HashMap<>();
		if(CollectionUtils.isNotEmpty(rows)){
			Object[] cells = (Object[])rows.get(0);
			map.put("id", cells[0]);
			map.put("type", cells[1]);
			map.put("city", cells[2]);
			map.put("date", cells[3]);
			map.put("time", cells[4]);
			map.put("description", cells[5]);
			String images = cells[6] == null? "" : cells[6].toString();
			String forbidImages = cells[7] == null? "" : cells[7].toString();
			List<Map<String, Object>> imagesList = new ArrayList<>();
			if(!StringUtils.isEmpty(images)){
				String[] imageArr = images.split(",");
				for(String image : imageArr){
					Map<String, Object> temp = new HashMap<>();
					temp.put("url", image);
					if(forbidImages.indexOf(image) >= 0){
						temp.put("forbidden", 1);
					}else{
						temp.put("forbidden", 0);
					}
					imagesList.add(temp);
				}
			}
			map.put("images", imagesList);
			map.put("createTime", cells[8]);
			map.put("likeNum", cells[9]);
			map.put("signNum", cells[10]);
			map.put("userId", cells[11]);
			map.put("nickname", cells[12]);
			map.put("sex", cells[13]);
			map.put("identity", cells[14]);
			map.put("avatar", cells[15]);
			map.put("isLiker", cells[16]);
			map.put("isSigner", cells[17]);
			map.put("isDating", cells[18]);
		}
		return map;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Map<String, Object> findById(Long broadCastId) {
		List rows = broadCastRepository.findById(broadCastId);
		Map<String, Object> map = new HashMap<>();
		if(CollectionUtils.isNotEmpty(rows)){
			Object[] cells = (Object[])rows.get(0);
			map.put("id", cells[0]);
			map.put("type", cells[1]);
			map.put("city", cells[2]);
			map.put("date", cells[3]);
			map.put("time", cells[4]);
			map.put("description", cells[5]);
			String images = cells[6] == null? "" : cells[6].toString();
			String forbidImages = cells[7] == null? "" : cells[7].toString();
			List<Map<String, Object>> imagesList = new ArrayList<>();
			if(!StringUtils.isEmpty(images)){
				String[] imageArr = images.split(",");
				for(String image : imageArr){
					Map<String, Object> temp = new HashMap<>();
					temp.put("url", image);
					if(forbidImages.indexOf(image) >= 0){
						temp.put("forbidden", 1);
					}else{
						temp.put("forbidden", 0);
					}
					imagesList.add(temp);
				}
			}
			map.put("images", imagesList);
			map.put("createTime", cells[8]);
			map.put("likeNum", cells[9]);
			map.put("signNum", cells[10]);
			map.put("userId", cells[11]);
			map.put("nickname", cells[12]);
			map.put("sex", cells[13]);
			map.put("identity", cells[14]);
			map.put("isDeleted", cells[15]);
		}
		return map;
	}
	
	@SuppressWarnings("rawtypes")
	public List<Map<String, Object>> findListBySex(Integer sex, String nickname, Integer page, Integer size){
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT ");
		sql.append("bc.id");
		sql.append(",bc.create_time");
		sql.append(",bc.user_id");
		sql.append(",usr.nickname");
		sql.append(",usr.identity");
		sql.append(",bc.date");
		sql.append(",bc.time");
		sql.append(",bc.city");
		sql.append(",usr.dating_money");
		sql.append(",(SELECT COUNT(1) FROM broast_cast_signer WHERE broad_cast_id = bc.id) signerNum");
		sql.append(",bc.is_deleted");
		sql.append(" FROM broad_cast bc");
		sql.append(" JOIN e_user usr ON bc.user_id = usr.id");
		sql.append(" WHERE usr.sex = :sex");
		if(!StringUtils.isEmpty(nickname)){
			sql.append(" AND usr.nickname LIKE CONCAT('%', CONCAT(:nickname, '%'))");
		}
		sql.append(" ORDER BY bc.create_time DESC");			
		sql.append(" LIMIT :pageIndex, :size");
		
		Query query = entityManager.createNativeQuery(sql.toString());
		query.setParameter("sex", sex);
		if(!StringUtils.isEmpty(nickname)){
			query.setParameter("nickname", nickname);
		}
		query.setParameter("pageIndex", (page-1)*size);
		query.setParameter("size", size);
		List resultList = query.getResultList();
		
		List<Map<String, Object>> list = new ArrayList<>();
		for(Object row : resultList){
			Object[] cells = (Object[]) row;
			Map<String, Object> map = new HashMap<>();
			map.put("id", cells[0]);
			map.put("createTime", cells[1]);
			map.put("userId", cells[2]);
			map.put("nickname", cells[3]);
			map.put("identity", cells[4]);
			map.put("date", cells[5]);
			map.put("time", cells[6]);
			map.put("city", cells[7]);
			map.put("datingMoney", cells[8]);
			map.put("signerNum", cells[9]);
			map.put("isDeleted", cells[10]);
			list.add(map);
		}
		
		return list;
	}

	@Override
	public Long countBySex(Integer sex, String nickname) {
		return broadCastRepository.countBySex(sex, nickname);
	}

}
